package cn.chencq.moudle.sys.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.chencq.constants.Constants;
import cn.chencq.moudle.sys.entity.SysUser;
import cn.chencq.moudle.sys.service.SysUserRoleService;
import cn.chencq.moudle.sys.service.SysUserService;
import cn.chencq.page.PageBean;
import cn.chencq.page.PageParam;
import cn.chencq.utils.R;
import cn.chencq.validator.Assert;
import cn.chencq.validator.ValidatorUtils;
import cn.chencq.validator.group.AddGroup;
import cn.chencq.validator.group.UpdateGroup;

/**
 * 系统用户
 * 
 * @author chenchaoqun
 * @email ccq@chencq.cn
 * @date 2018-10-22 15:41:40
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;

	/**
	 * 所有用户列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R list(@ModelAttribute PageParam pageParam) {
		Map<String, Object> params = pageParam.getParams();
		// 只有超级管理员，才能查看所有管理员列表
		if (getUserId() != Constants.SUPER_ADMIN) {
			params.put("createUserId", getUserId());
		}
		PageBean page = sysUserService.listPage(pageParam);
		return R.ok().put("page", page).put("params", params);
	}

	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
	public R info() {
		return R.ok().put("user", getUser());
	}

	/**
	 * 修改登录用户密码
	 */
	@PostMapping("/password")
	public R password(String password, String newPassword) {
		Assert.isBlank(newPassword, "新密码不为能空");

		// sha256加密
		password = new Sha256Hash(password, getUser().getSalt()).toHex();
		// sha256加密
		newPassword = new Sha256Hash(newPassword, getUser().getSalt()).toHex();

		// 更新密码
		boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
		if (!flag) {
			return R.error("原密码不正确");
		}

		return R.ok();
	}

	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") Long userId) {
		SysUser user = sysUserService.selectByPrimaryKey(userId);

		// 获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);

		return R.ok().put("user", user);
	}

	/**
	 * 保存用户
	 */
	@PostMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R save(@RequestBody SysUser user) {
		ValidatorUtils.validateEntity(user, AddGroup.class);

		user.setCreateUserId(getUserId());
		sysUserService.save(user);

		return R.ok();
	}

	/**
	 * 修改用户
	 */
	@PostMapping("/update")
	@RequiresPermissions("sys:user:update")
	public R update(@RequestBody SysUser user) {
		ValidatorUtils.validateEntity(user, UpdateGroup.class);

		user.setCreateUserId(getUserId());
		sysUserService.updateByPrimaryKey(user);

		return R.ok();
	}

	/**
	 * 删除用户
	 */
	@PostMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long[] userIds) {
		if (ArrayUtils.contains(userIds, 1L)) {
			return R.error("系统管理员不能删除");
		}

		if (ArrayUtils.contains(userIds, getUserId())) {
			return R.error("当前用户不能删除");
		}

		if (Objects.nonNull(userIds) && userIds.length > 0) {
			List<Long> userIdList = Arrays.asList(userIds);
			sysUserService.batchDeleteByPks(userIdList);
		}

		return R.ok();
	}
}
